/**
 * Created by xstnet on 2018/7/1.
 * Author: xstnet
 */
import React from 'react';
import { connect } from 'react-redux'
import { Table, Button, Switch, Modal, Form, Input, TreeSelect, Icon, Popconfirm } from 'antd';
import { getPermission, changeStatus, savePermission, deletePermission } from '@/api/Api.js'
import { getFormItemLayout, getModalTitle } from '../../utils/CommonUtil'

const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const formItemLayout = getFormItemLayout(24, 4, 24, 20);

const mapStateToProps = (state, ownProps) => ({
	permission: state.Permission.permission,
	menuList: state.common.menuList,
})

const ADD_TITLE = <span className='modal-title'><Icon type='plus'/> 添加节点</span>
const EDIT_TITLE = <span className='modal-title'><Icon type='edit'/> 编辑节点</span>

// rowSelection objects indicates the need for row selection
const rowSelection = {
	onChange: (selectedRowKeys, selectedRows) => {
		console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
	},
	onSelect: (record, selected, selectedRows) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (selected, selectedRows, changeRows) => {
		console.log(selected, selectedRows, changeRows);
	},
	getCheckboxProps: record => ({
		disabled: !record.isNode,
		name: record.name,
	}),
}


class Permission extends React.Component {
	constructor(props) {
		super(props);
	}
	state = {
		loading: true,
		visible: false,
		actionTitle: ADD_TITLE,
		actionType: '',
		node: {
			menu_id: '',
			name: '',
			url: '',
			description: '',
		},
	}

	columns = [
		{
		title: '权限',
		dataIndex: 'name',
		key: 'name',
		render: (text, record) => {
			return record.isNode ? this.props.permission.data[ record.key ].name : text;
		}
	}, {
		title: 'url',
		dataIndex: 'url',
		// width: '',
		key: 'url',
		render: (text, record) => {
			return record.isNode ? this.props.permission.data[ record.key ].url : '';
		}
	}, {
		title: '描述',
		dataIndex: 'description',
		// width: '10%',
		key: 'description',
		render: (text, record) => {
			return record.isNode ? this.props.permission.data[ record.key ].description : '';
		}
	}, {
		title: '状态',
		align: 'center',
		dataIndex: 'status',
		width: 120,
		key: 'status',
		render: (text, record) => {
			let item = this.props.permission.data[ record.key ];
			return record.isNode ?
				(<Switch checkedChildren="启用" onChange={this.handleChangeStatus.bind(this, item)} unCheckedChildren="禁用" checked={!parseInt(item.status)} />)
				: ''
		},
	},{
		title: '添加时间',
		align: 'center',
		dataIndex: 'created_at',
		width: 160,
		key: 'created_at',
		render: (text, record) => {
			return record.isNode ? this.props.permission.data[ record.key ].created_at : '';
		},
	}, {
		title: '操作',
		align: 'center',
		key: 'operation',
		width: 180,
		render: (text, record) => {
			return record.isNode ?
				(<span>
					<Button type="primary" onClick={this.onEdit.bind(this, this.props.permission.data[record.key])} style={{marginRight: 10}} icon="edit" size='small'>编辑</Button>
					<Popconfirm title="Are you sure delete this Permission?" onConfirm={this.onDelete.bind(this, record.key)} okText="Yes" cancelText="No">
						<Button type="danger" size='small' icon="delete" htmlType="button">删除</Button>
					</Popconfirm>
				</span>)
				: ''
		},
	},
	];

	/**
	 * 渲染菜单树结构
	 * @param data 菜单列表
	 * @returns Nodes
	 */
	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.child) {
				return (
					<TreeNode title={item.name} key={item.url} value={item.id} dataRef={item}>
						{this.renderTreeNodes(item.child)}
					</TreeNode>
				);
			}
			item.title = item.name;
			item.key = item.url;
			item.value = item.id;
			return <TreeNode {...item} />;
		});
	}

	handleChangeStatus = (record, checked) => {
		if (record.key) {
			let permission = this.props.permission
			changeStatus(record.key, permission, record.key, checked).then(result => {
			})
		}
		return false;
	}

	handleDelete = () => {
		alert('还没做呢！')
	}
	/**
	 * 点击添加 响应
	 */
	onAdd = () => {
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: ADD_TITLE,
			actionType: 'add',
		});
		this.props.form.setFieldsValue(this.state.node);
	}
	/**
	 * 点击编辑 响应
	 */
	onEdit = item => {
		console.log(item)
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: EDIT_TITLE,
			actionType: 'save',
			node: {
				...this.state.node,
				menu_id: item.menu_id,
			},
		});
		this.props.form.setFieldsValue(item);
	}

	onDelete = (id, event) => {
		deletePermission(id)
	}
	/**
	 * 添加/保存 结点
	 * @param e
	 */
	handleSave = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (err) {
				console.log(err);
				return false;
			}
			savePermission(this.state.actionType, values).then(result => {
				if (this.state.actionType === 'save') {
					this.setState({
						visible: false,
					});
				}
			});
		})
	}

	handleCancel = (e) => {
		let node = false;
		if (this.state.actionType === 'add') {
			node = this.props.form.getFieldsValue();
			delete node.id;
		}
		this.setState({
			visible: false,
			node: node ? node : this.state.node,
		});
	}
	/**
	 * 选择菜单
	 * @param value
	 */
	handleChangeMenu = menu_id => {
		if (menu_id) {
			let node = this.state.node;
			node.menu_id = menu_id;
			this.setState({ node });
			this.props.form.setFieldsValue({menu_id});
		}
	}

	componentDidMount() {
		getPermission().then(result => {
			this.setState({loading: false})
		})
	}
	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div style={{ minHeight: 800 }}>
				<Button onClick={this.onAdd} icon='plus' type="primary" style={{ marginBottom: 16, marginRight:16 }}>
					添加
				</Button>
				<Button onClick={this.handleDelete} type="danger" icon='delete' style={{ marginBottom: 16 }}>
					删除
				</Button>
				<Table
					columns={this.columns}
					rowSelection={rowSelection}
					dataSource={this.props.permission.tree}
					loading={this.state.loading}
					className='bg-white'
					// rowKey="id"
					bordered
					title={() => '权限列表'}
					size="small"
				/>
				<div>
					<Modal
						title={this.state.actionTitle}
						visible={this.state.visible}
						onOk={this.handleSave}
						onCancel={this.handleCancel}
						okText="保存"
						cancelText="取消"
					>
						<Form>
							<FormItem {...formItemLayout} label="所属菜单">
								{getFieldDecorator('menu_id', {
									rules: [{
										required: true, message: '请选择所属菜单',
										initialValue: '',
									}],})(<Input type='hidden' />)}
								<TreeSelect
									showSearch placeholder="请选择所属菜单"
									// allowClear
									value={this.state.node.menu_id}
									treeNodeFilterProp='title'
									onChange={this.handleChangeMenu}
								>
									<TreeNode value="0" title="其他" key="/other" />
									{this.renderTreeNodes(this.props.menuList)}
								</TreeSelect>
							</FormItem>
							<FormItem {...formItemLayout} label="名称">
								{getFieldDecorator('name', {
									rules: [{
										required: true, message: '请输入名称',
									}],
								})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="路由">
								{getFieldDecorator('url', {
									rules: [{
										required: true, message: '请输入路由',
									}],
								})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="描述">
								{getFieldDecorator('description', {
									initialValue: '',
								})(<Input />)}
							</FormItem>
							<span>
								{getFieldDecorator('id', {
									initialValue: '0',
								})(<Input type='hidden' />)}
							</span>
						</Form>
					</Modal>
				</div>
			</div>);
	}
}

export default connect(
	mapStateToProps,
	// mapDispatchToProps
)(Form.create()(Permission))